
const { errorCode } = require('../../../common/constans/errorCodeConstants')

exports.processMsg = async function (msgInfo) {
    let retMsgInfo = msgInfo
    retMsgInfo.gmtResponse = new Date()
    const proccessor = getProccessorByTopicName(msgInfo.topic)
    if (proccessor == null) {
        retMsgInfo.success = false
        retMsgInfo.errorCode = errorCode.NO_PROCCESSOR
        return retMsgInfo
    }

    let body = null
    if (proccessor.constructor.name == "AsyncFunction") {
        body = await proccessor(msgInfo.payload)
    } else {
        body = proccessor(msgInfo.payload)
    }
    retMsgInfo.body = body
    retMsgInfo.success = true
    return retMsgInfo
}


function getProccessorByTopicName(topic) {
    // topic格式为类似userService.slogan.getSlogan，通过动态从biz目录下获取处理器，以最后一个作为方法名
    const proccessorPath = '../../' + topic.replace(new RegExp('\\.', "g"), '/')
    try {
        const proccessor = require(proccessorPath)
        functionName = topic.split(".").pop()
        for (let func in proccessor) {
            if (func == functionName) {
                return proccessor[func]
            }
        }
        return null

    } catch (e) {
        return null
    }
}
